<template>
  <Dialog v-model:visible="visible" modal :header="title" :style="{ width: '90vw' }">
    <div>Name/Address: <InputText v-model="editingStream.name"></InputText></div>
    <Divider />
    <Chip v-for="(i, index) in editingStream.basicConfigs" :key="index">
      {{ i.code + '  ' + i.value + ';'
      }}<i class="pi pi-minus-circle" @click="deleteBasicConfigFn(i)" />
    </Chip>
    <Divider />
    <basic-config-add :options="options" @confirm="addBasicConfigFn"></basic-config-add>
    <template #footer>
      <Button label="Save" icon="pi pi-save" @click="newStreamFn" />
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import type { BasicConfig, HttpStreamConfig } from '@/types/dt/Dt.ts'
import BasicConfigAdd from '@/views/tools/nginx/detail-comps/basic-config-add.vue'
import { ref } from 'vue'
import { streamUpstreamBasicOptions } from '@/views/tools/nginx/data/stream_basic_options.ts'

const options = [
  ...streamUpstreamBasicOptions
]
const visible = ref(false)

const title = ref('')
let resolve: ((a: any) => void) | undefined
let reject: ((e: Error) => void) | undefined
const editingStream = ref<HttpStreamConfig>({
  name: 'new-stream',
  basicConfigs: [],
})

function newStreamFn() {
  if (typeof resolve === 'function') {
    resolve(JSON.parse(JSON.stringify(editingStream.value)))
  }
  editingStream.value.basicConfigs = []
  editingStream.value.name = 'new-stream'
  visible.value = false
  resolve = undefined
  reject = undefined
}

function addBasicConfigFn(c: BasicConfig) {
  editingStream.value.basicConfigs.push(c)
}
function deleteBasicConfigFn(c: BasicConfig) {
  editingStream.value.basicConfigs = editingStream.value.basicConfigs.filter( item => item !== c)
}

function open(c?: HttpStreamConfig): Promise<HttpStreamConfig> {
  if (c){
    title.value = 'Edit Stream Upstream'
    editingStream.value = JSON.parse(JSON.stringify(c))
  } else {
    title.value = 'Add Stream Upstream'
    editingStream.value = {
      name: 'new-stream',
      basicConfigs: [],
    }
  }
  visible.value = true
  return new Promise((r, re) => {
    resolve = r
    reject = re
  })
}
defineExpose({
  open:open
})
</script>

<style scoped></style>
